// const http = require('http');
// const hostname = '127.0.0.1';
// const port = 3000;
// const server = http.createServer(function (req, res) {
//   res.statusCode = 200;
//   res.setHeader('Content-Type', 'text/plain');
//   res.end('Hello World\n');
// });
// server.listen(port, hostname, function () {
//   console.log('Server running at http://' + hostname + ':' + port + '/');
// });

const express = require('express')
const fs = require('fs')
var bodyParser = require('body-parser')

const app = express()
var isBegin = true
app.use(express.static('public'));
// app.use(express.json())
app.use(bodyParser.text({ type: 'text/html' }))
// app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
// app.use(bodyParser.json({ limit: '50mb', extended: true }))
app.set('view engine', 'ejs')

app.post('/data', function (req, res) {
  if (isBegin) {
    isBegin = false
    fs.appendFile('message.json', "{", (err) => {
      fs.appendFile('message.json', req.body, (err) => {
        if (err) throw err;
        res.send()
      });
    })
  } else {
    fs.appendFile('message.json', req.body, (err) => {
      if (err) throw err;
      res.send()
    });
  }
})

app.get('/done', function (req, res) {
  console.log('Export done.')
  fs.appendFile('message.json', '}', (err) => {
    if (err) throw err;
    res.send()
  })
})

app.get('/', function (req, res) {
  res.render('index')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})